package com.ls.data.controller;

import com.alibaba.fastjson.JSONObject;
import com.ls.data.service.*;
import com.ls.interPojo.Weather;
import com.ls.pojo.CustInter;
import com.ls.pojo.Customer;
import com.ls.pojo.Inter;
import com.ls.pojo.InterThirdparty;
import com.ls.utils.HttpClientUtils;
import com.ls.utils.Result;
import com.ls.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 段成
 * @date 2020/1/9 - 9:11
 */
@RestController
@RequestMapping(value = "/weather")
public class WeatherController {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private InterfaceService interfaceService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CustomerInterfaceService customerInterfaceService;

    @Autowired
    private WeatherService weatherService;

    @Autowired
    private InterThirdpartyService interThirdpartyService;


    @GetMapping("/getData")
    public Result getData(@RequestParam(name = "city",defaultValue = "") String city, @RequestParam(name = "appkey",defaultValue = "") String appkey){
        if("".equals(appkey) || null == appkey || "".equals(city) || null == city){
            return new Result(false, StatusCode.PARAMETER_IS_EMPTY,"参数为空");
        }

        try {
            //  通过地址查询接口id
            StringBuffer requestURL = null;
            requestURL = request.getRequestURL();
            Inter inter = interfaceService.getInterfaceByURL(requestURL.toString());
            if(inter == null){
                return new Result(false, StatusCode.ERROR,"接口不存在");
            }

            CustInter custInter = customerInterfaceService.getAppkeyByAppkey(appkey,inter.getId());

            // 为null 则没有这条记录  appkey不存在或错误
            if(custInter == null){
                return new Result(false, StatusCode.ERROR,"appkey不存在或错误");
            }else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
                String currentTime = sdf.format(System.currentTimeMillis());
                //查询此城市是否有数据
                List<Weather> weatherList = weatherService.getDataByCity(city);
                if(weatherList.size()>0){
                    for (Weather weather : weatherList) {
                        //查询此时间点是否有数据
                        if(weather.getSdate().equals(currentTime)){
                            System.out.println("本地数据");
                            return new Result(true, StatusCode.OK,"本地查询成功",weather,null);
                        }
                    }
                }

                System.out.println("本地没有则第三方查询  主1从2辅3");
                //本地没有则第三方查询  主1从2辅3
                InterThirdparty interThirdparty1 = interThirdpartyService.getListByInterfaceId(inter.getId(),1);
                //沉淀数据
                Weather insertData = this.StitchingAddress(interThirdparty1, city);


                return new Result(true, StatusCode.OK,"第三方查询成功",insertData,null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"查询失败出现异常");
        }


    }

    private Weather StitchingAddress(InterThirdparty interThirdparty, String city) {
        //请求第三方数据
        StringBuffer reqUrl = new StringBuffer();
        reqUrl.append(interThirdparty.getThirdpartyUrl());
        reqUrl.append("?city=");
        reqUrl.append(city);
        reqUrl.append("&key=");
        reqUrl.append(interThirdparty.getAppkey());
        System.out.println(reqUrl.toString());
        JSONObject jsonObject = HttpClientUtils.httpGet(reqUrl.toString());
        Map map = (Map)jsonObject.get("result");
        String realtime = map.get("realtime").toString();
        String future = map.get("future").toString();
        //沉淀数据
        Weather insertData = new Weather();
        insertData.setCity(city);
        insertData.setFuture(future);
        insertData.setRealtime(realtime);
        insertData.setSdate(new Date());
        weatherService.insertData(insertData);
        System.out.println(jsonObject.toString());
        return insertData;
    }
}
